package String;

/**
 * @author 孤雪唯方
 * @date 2025/05/18
 * @description 字符串分割
 */
public class StringSplit {

    /**
     * 多次拆分字符串，并打印出每个元素
     */
    public static void split() {
        String str = "name=jack&age=20";
        String[] arr = str.split("&");
        for (String s : arr) {
            String[] arr2 = s.split("=");
            System.out.println(arr2[0] + " : " + arr2[1]);
        }
    }

    public static void main(String[] args) {
        //定义字符串
        String str1 = "abc";
        String str2 = "123,456,789";
        String str3 = "987 456 321";
        String str4 = "127.0.0.1:8080";
        String str5 = "Hello World 123 456 789";

        //以固定方式分割字符串
        String[] strArr1 = str1.split("");// 空字符串分割,即按字符分割
        String[] strArr2 = str2.split(",");// 逗号分割
        String[] strArr3 = str3.split(" ");// 空格分割
        String[] strArr4 = str4.split("\\.");// 点分割，如果需要按".","|","*","+"等字符分割，则需要加上转义字符，在前面加上"\\",如果是想通过"\"分割，则需要用"\\\\"
        String[] strArr5 = str5.split(" ", 2);// 空格分割,分割成两个元素，即在遇到空格时停止，将空格前的元素作为第一个元素，空格后的元素作为第二个元素


        //输出分割后的字符串
        for (String s : strArr1) {
            System.out.println(s);
        }
        for (String s : strArr2) {
            System.out.println(s);
        }
        for (String s : strArr3) {
            System.out.println(s);
        }
        for (String s : strArr4) {
            System.out.println(s);
        }
        for (String s : strArr5) {
            System.out.println(s);
        }
        //调用split()方法
        split();
        System.out.println("=============================");
        String str6 = " hello world ";
        System.out.println("[" + str6.trim() + "]");
        System.out.println("[" + str6 + "]");
    }
}
